package net.zoneland.zrdp.common.xss;

import org.apache.commons.lang3.StringUtils;


import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 自定义xss校验注解实现
 *
 * @author zonevue
 */
public class XssValidator implements ConstraintValidator<Xss, String>
{
    private static final String HTML_PATTERN = ".*<(\\S*?)[^>]*>.*?|<.*? />.*";
    private static final Pattern pattern = Pattern.compile(HTML_PATTERN);

    @Override
    public boolean isValid(final String value, final ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(value)) {
            return true;
        }
        return !containsHtml(value);
    }

    public static boolean containsHtml(final String value) {
        final Matcher matcher = pattern.matcher(value);
        return matcher.matches();
    }
}
